home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Resources / Chat & Communication / Digsby build 37 / digsby_setup.exe / lib / ZSI / twisted / wsgi.pyo (.txt) < prev    next >
Python Compiled Bytecode  |  2008-10-13  |  9KB  |  272 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. import os
  5. import sys
  6. import types
  7. import inspect
  8. from StringIO import StringIO
  9. from zope.interface import classProvides, implements, Interface
  10. from ZSI import _get_element_nsuri_name, EvaluateException, ParseException, fault, ParsedSoap, SoapWriter
  11. from ZSI.twisted.reverse import DataHandler, ReverseHandlerChain, HandlerChainInterface
  12.  
  13. def soapmethod(requesttypecode, responsetypecode, soapaction = '', operation = None, **kw):
  14.     
  15.     def _closure(func_cb):
  16.         func_cb.root = (requesttypecode.nspname, requesttypecode.pname)
  17.         func_cb.action = soapaction
  18.         func_cb.requesttypecode = requesttypecode
  19.         func_cb.responsetypecode = responsetypecode
  20.         func_cb.soapmethod = True
  21.         func_cb.operation = None
  22.         return func_cb
  23.  
  24.     return _closure
  25.  
  26.  
  27. class SOAPCallbackHandler:
  28.     classProvides(HandlerChainInterface)
  29.     writerClass = None
  30.     
  31.     def processRequest(cls, ps, **kw):
  32.         resource = kw['resource']
  33.         request = kw['request']
  34.         root = _get_element_nsuri_name(ps.body_root)
  35.         for key, method in inspect.getmembers(resource, inspect.ismethod):
  36.             if getattr(method, 'soapmethod', False) and method.root == root:
  37.                 break
  38.                 continue
  39.         else:
  40.             raise RuntimeError, 'Missing soap callback method for root "%s"' % root
  41.         
  42.         try:
  43.             req = ps.Parse(method.requesttypecode)
  44.         except Exception:
  45.             ex = None
  46.             raise 
  47.  
  48.         
  49.         try:
  50.             rsp = method.responsetypecode.pyclass()
  51.         except Exception:
  52.             ex = None
  53.             raise 
  54.  
  55.         
  56.         try:
  57.             (req, rsp) = method(req, rsp)
  58.         except Exception:
  59.             ex = None
  60.             raise 
  61.  
  62.         return rsp
  63.  
  64.     processRequest = classmethod(processRequest)
  65.     
  66.     def processResponse(cls, output, **kw):
  67.         sw = SoapWriter(outputclass = cls.writerClass)
  68.         sw.serialize(output)
  69.         return sw
  70.  
  71.     processResponse = classmethod(processResponse)
  72.  
  73.  
  74. class SOAPHandlerChainFactory:
  75.     protocol = ReverseHandlerChain
  76.     
  77.     def newInstance(cls):
  78.         return cls.protocol(DataHandler, SOAPCallbackHandler)
  79.  
  80.     newInstance = classmethod(newInstance)
  81.  
  82.  
  83. class WSGIApplication(dict):
  84.     encoding = 'UTF-8'
  85.     
  86.     def __call__(self, env, start_response):
  87.         script = env['SCRIPT_NAME']
  88.         ipath = os.path.split(env['PATH_INFO'])[1:]
  89.         for i in range(1, len(ipath) + 1):
  90.             path = os.path.join(*ipath[:i])
  91.             print 'PATH: ', path
  92.             application = self.get(path)
  93.             if application is not None:
  94.                 env['SCRIPT_NAME'] = script + path
  95.                 env['PATH_INFO'] = ''
  96.                 print 'SCRIPT: ', env['SCRIPT_NAME']
  97.                 return application(env, start_response)
  98.                 continue
  99.         
  100.         return self._request_cb(env, start_response)
  101.  
  102.     
  103.     def _request_cb(self, env, start_response):
  104.         start_response('404 ERROR', [
  105.             ('Content-Type', 'text/plain')])
  106.         return [
  107.             'Move along people, there is nothing to see to hear']
  108.  
  109.     
  110.     def putChild(self, path, resource):
  111.         path = path.split('/')
  112.         lp = len(path)
  113.         if lp == 0:
  114.             raise RuntimeError, 'bad path "%s"' % path
  115.         
  116.         if lp == 1:
  117.             self[path[0]] = resource
  118.         
  119.         for i in range(len(path)):
  120.             if not path[i]:
  121.                 continue
  122.             
  123.             break
  124.         
  125.         next = self.get(path[i], None)
  126.         if next is None:
  127.             next = self[path[i]] = WSGIApplication()
  128.         
  129.         next.putChild('/'.join(path[-1:]), resource)
  130.  
  131.  
  132.  
  133. class SOAPApplication(WSGIApplication):
  134.     factory = SOAPHandlerChainFactory
  135.     
  136.     def __init__(self, **kw):
  137.         dict.__init__(self, **kw)
  138.         self.delegate = None
  139.  
  140.     
  141.     def _request_cb(self, env, start_response):
  142.         if env['REQUEST_METHOD'] == 'GET':
  143.             return self._handle_GET(env, start_response)
  144.         
  145.         if env['REQUEST_METHOD'] == 'POST':
  146.             return self._handle_POST(env, start_response)
  147.         
  148.         start_response('500 ERROR', [
  149.             ('Content-Type', 'text/plain')])
  150.         s = StringIO()
  151.         h = env.items()
  152.         h.sort()
  153.         for k, v in h:
  154.             print >>s, k, '=', `v`
  155.         
  156.         return [
  157.             s.getvalue()]
  158.  
  159.     
  160.     def _handle_GET(self, env, start_response):
  161.         if env['QUERY_STRING'].lower() == 'wsdl':
  162.             start_response('200 OK', [
  163.                 ('Content-Type', 'text/plain')])
  164.             if not self.delegate:
  165.                 pass
  166.             r = self
  167.             return _resourceToWSDL(r)
  168.         
  169.         start_response('404 ERROR', [
  170.             ('Content-Type', 'text/plain')])
  171.         return [
  172.             'NO RESOURCE FOR GET']
  173.  
  174.     
  175.     def _handle_POST(self, env, start_response):
  176.         input = env['wsgi.input']
  177.         data = input.read(int(env['CONTENT_LENGTH']))
  178.         mimeType = 'text/xml'
  179.         if self.encoding is not None:
  180.             mimeType = 'text/xml; charset="%s"' % self.encoding
  181.         
  182.         request = None
  183.         if not self.delegate:
  184.             pass
  185.         resource = self
  186.         chain = self.factory.newInstance()
  187.         
  188.         try:
  189.             pyobj = chain.processRequest(data, request = request, resource = resource)
  190.         except Exception:
  191.             ex = None
  192.             start_response('500 ERROR', [
  193.                 ('Content-Type', mimeType)])
  194.             return [
  195.                 fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()]
  196.  
  197.         
  198.         try:
  199.             soap = chain.processResponse(pyobj, request = request, resource = resource)
  200.         except Exception:
  201.             ex = None
  202.             start_response('500 ERROR', [
  203.                 ('Content-Type', mimeType)])
  204.             return [
  205.                 fault.FaultFromException(ex, False, sys.exc_info()[2]).AsSOAP()]
  206.  
  207.         start_response('200 OK', [
  208.             ('Content-Type', mimeType)])
  209.         return [
  210.             soap]
  211.  
  212.  
  213.  
  214. def test(app, port = 8080, host = 'localhost'):
  215.     reactor = reactor
  216.     import twisted.internet
  217.     log = log
  218.     import twisted.python
  219.     HTTPFactory = HTTPFactory
  220.     import twisted.web2.channel
  221.     Site = Site
  222.     import twisted.web2.server
  223.     WSGIResource = WSGIResource
  224.     import twisted.web2.wsgi
  225.     log.startLogging(sys.stdout)
  226.     reactor.listenTCP(port, HTTPFactory(Site(WSGIResource(app))), interface = host)
  227.     reactor.run()
  228.  
  229.  
  230. def _issoapmethod(f):
  231.     if type(f) is types.MethodType:
  232.         pass
  233.     return getattr(f, 'soapmethod', False)
  234.  
  235.  
  236. def _resourceToWSDL(resource):
  237.     ElementTree = ElementTree
  238.     import xml.etree
  239.     Element = Element
  240.     QName = QName
  241.     import xml.etree.ElementTree
  242.     WSDL = WSDL
  243.     import ZSI.wstools.Namespaces
  244.     r = resource
  245.     methods = filter(_issoapmethod, (map,)((lambda i: getattr(r, i)), dir(r)))
  246.     tns = ''
  247.     defs = Element('{%s}definitions' % WSDL.BASE)
  248.     defs.attrib['name'] = 'SampleDefs'
  249.     defs.attrib['targetNamespace'] = tns
  250.     porttype = Element('{%s}portType' % WSDL)
  251.     porttype.attrib['name'] = QName('{%s}SamplePortType' % tns)
  252.     binding = Element('{%s}binding' % WSDL)
  253.     defs.append(binding)
  254.     binding.attrib['name'] = QName('{%s}SampleBinding' % tns)
  255.     binding.attrib['type'] = porttype.get('name')
  256.     for m in methods:
  257.         m.action
  258.     
  259.     service = Element('{%s}service' % WSDL.BASE)
  260.     defs.append(service)
  261.     service.attrib['name'] = 'SampleService'
  262.     port = Element('{%s}port' % WSDL.BASE)
  263.     service.append(port)
  264.     port.attrib['name'] = 'SamplePort'
  265.     port.attrib['binding'] = binding.get('name')
  266.     soapaddress = Element('{%s}address' % WSDL.BIND_SOAP)
  267.     soapaddress.attrib['location'] = 'http://localhost/bla'
  268.     port.append(soapaddress)
  269.     return [
  270.         ElementTree.tostring(defs)]
  271.  
  272.